package com.zhang;

import cn.hutool.core.util.StrUtil;
import com.zhang.common.Constant;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务端跟客户端连接的channel  通过域名跟channel对应   域名不能重复
 * @author zhanghao
 */
public class ClientChannelManage {
    /**
     * 日志对象
     */
    static private Logger log = LoggerFactory.getLogger(ClientChannelManage.class);
    /**
     * 域名跟channel建立对应关系
     */
    static private Map<String, Channel> _DomainChannel = new ConcurrentHashMap<>();
    /**
     * 私有化构造器
     */
    private ClientChannelManage(){}

    /**
     * 通过域名获取channel
     * @param domain
     * @return
     */
    public static Channel getChannelByDomain(String domain){
        if(StrUtil.isBlank(domain)){
            return null;
        }

        return _DomainChannel.get(domain);
    }

    /**
     * 添加域名和channel的映射关系
     */
    public static void addDomainAndChannel(String domain,Channel channel){
        if (StrUtil.isBlank(domain) || null == channel){
            return;
        }
        channel.attr(Constant.DOMAIN).set(domain);
        _DomainChannel.put(domain,channel);
    }

    /**
     * 通过域名移除 channel
     * @param domain
     */
    public static void removeChannelByDomain(String domain){
        _DomainChannel.remove(domain);
    }
}
